﻿using SkiaSharp;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using static System.Net.Mime.MediaTypeNames;

namespace ImageSkiaSharp
{
    internal class ImageHelp
    {
        /// <summary>
        /// 压缩图片
        /// </summary>
        /// <param name="source">原文件位置</param>
        /// <param name="target">生成目标文件位置</param>
        /// <param name="maxWidth">最大宽度，根据此宽度计算是否需要缩放，计算新高度</param>
        /// <param name="quality">图片质量，范围0-100</param>
        public static void Compress(string source, string target, decimal maxWidth, int quality)
        {
            using (var file = File.OpenRead(source))
            using (var fileStream = new SKManagedStream(file))
            using (var bitmap = SKBitmap.Decode(fileStream))
            {
                var width = (decimal)bitmap.Width;
                var height = (decimal)bitmap.Height;
                var newWidth = width;
                var newHeight = height;
                if (width > maxWidth)
                {
                    newWidth = maxWidth;
                    newHeight = height / width * maxWidth;
                }
                using (var resized = bitmap.Resize(new SKImageInfo((int)newWidth, (int)newHeight), SKSamplingOptions.Default))
                {
                    if (resized != null)
                    {
                        using (var image = SKImage.FromBitmap(resized))
                        using (var writeStream = File.OpenWrite(target))
                        {
                            image.Encode(SKEncodedImageFormat.Jpeg, quality).SaveTo(writeStream);
                        }
                    }
                }
            }
        }
    }
}
